<template>
	<view class="details" :style="{paddingTop: paddingHeight + 'px'}">
		<nav-bar></nav-bar>
		<view class="t-h-container">
			<view class="t-h-title">
				{{ handleType == 'add' ? '睡眠记录' : '编辑睡眠记录' }}
			</view>
			<view class="t-h-sub-title" v-if="handleType == 'add'">
				填写上床时间以及起床时间以确认您当天的夜间睡眠时长
			</view>
			<view class="update_time">
				{{ today }}
			</view>
			<view class="wakeDown">
				<!-- <view class="days_tabs">
					<view class="day" @click="type = 'yesterday'" :class="{current: type == 'yesterday'}">
						昨天
					</view>
					<view class="day" :class="{current: type == 'today'}">
						今天
					</view>
				</view> -->
				<view class=" d_t" @click="showWakeDownTime = true">
					<view class="t-l">
						上床时间
					</view>
					<view class="t-r">
						<view class="time">
							{{ wakeDownTime }}
						</view>
						<view class="b-border"></view>
					</view>
				</view>
			</view>
			<view class="wakeUp">
				<view class="u_t" @click="showWakeUpTime = true">
					<view class="t-l">
						起床时间
					</view>
					<view class="t-r">
						<view class="time">
							{{ wakeUpTime }}
						</view>
						<view class="b-border"></view>
					</view>
				</view>
			</view>
		</view>
		<view class="large_button" @click="$u.throttle(add, 1500)" v-if="handleType == 'add'">
			完成
		</view>
		<view class="handle_c" v-else>
			<view class="delete_btn" @click="$u.throttle(del, 1500)">
				删除
			</view>
			<view class="save_btn" @click="$u.throttle(update, 1500)">
				保存
			</view>
		</view>
		<u-datetime-picker @confirm="selectWakeUpTime" @cancel="showWakeUpTime = false" @close="showWakeUpTime = false"
			closeOnClickOverlay :show="showWakeUpTime" v-model="wakeUpTime" mode="time"></u-datetime-picker>
		<u-datetime-picker @confirm="selectWakeDownTime" @cancel="showWakeDownTime = false"
			@close="showWakeDownTime = false" :show="showWakeDownTime" v-model="wakeDownTime" closeOnClickOverlay
			mode="time"></u-datetime-picker>
	</view>
</template>

<script>
	import {
		addSleepRecord,
		findSleepDayRecord,
		updateSleepRecord,
		delSleepRecord
	} from '@/api/index.js'
import { mapGetters  } from 'vuex'
	const dayjs = require('@/utils/dayjs.min.js');
	export default {
		data() {
			return {
				paddingHeight: uni.getStorageSync('navbarHeight'),
				userId: uni.getStorageSync("userId"),
				handleType: '',
				recordId: '', // 当前睡眠记录id
				type: 'today',
				today: '', // 当天日期
				showWakeUpTime: false,
				showWakeDownTime: false,
				wakeDownTime: '00:00',
				wakeUpTime: '00:00'
			}
		},
        computed: {
        ...mapGetters ({
            userInfo: 'getUserInfo'
        }),
    },
		onLoad(OPTIONS) {
			console.log(OPTIONS);
			if (OPTIONS.status == 'current') { // 操作当天睡眠记录
				this.today = dayjs().format('YYYY/MM/DD')
				this.fetchData()
			} else {
				let obj = JSON.parse(OPTIONS.info)
				if (!obj.id) { // 添加
					this.handleType = 'add'
					this.today = dayjs(obj.createTimeStr).format('YYYY/MM/DD')
				} else {
					this.handleType = 'update'
					this.recordId = obj.id
					this.today = obj.createTimeStr.replaceAll('-', '/')
					if (obj.startFullTime.substr(0, 10) != obj.endFullTime.substr(0, 10)) {
						this.type = 'yesterday'
					} else {
						this.type = 'today'
					}
					this.wakeDownTime = obj.startFullTime.split(' ')[1].substr(0, 5)
					this.wakeUpTime = obj.endFullTime.split(' ')[1].substr(0, 5)
				}
			}
		},
		methods: {
			async fetchData() {
				uni.showLoading({
					title: '加载中...'
				})
				let params = {
					userId: this.userId
				}
				try {
					const res = await findSleepDayRecord(params)
					if (res.code == 200) {
						if (!res.data) { // 无记录为添加
							this.handleType = 'add'
						} else { // 有记录修改
							this.handleType = 'update'
							if (res.data.startTime.substr(0, 10) != res.data.endTime.substr(0, 10)) {
								this.type = 'yesterday'
							} else {
								this.type = 'today'
							}
							this.wakeDownTime = res.data.startTime.split(' ')[1].substr(0, 5)
							this.wakeUpTime = res.data.endTime.split(' ')[1].substr(0, 5)
							this.recordId = res.data.id
						}
					}
				} catch (e) {
					//TODO handle the exception
				}
				uni.hideLoading()
			},
			async add() {
				uni.showLoading({
					title: '加载中...'
				})
				let today = this.today.replaceAll('/', '-')
				let params = {
					userId: this.userId,
					bodyId: this.userInfo.id,
					endTime: '',
					startTime: ''
				}
                if (this.wakeDownTime == '00:00' &&this.wakeUpTime == '00:00') {
                    this.wakeUpTime = '23:59'
                }
				params.endTime = `${today} ${this.wakeUpTime}:00`
				// let yesterday = dayjs(dayjs(today).subtract(1, 'day')).format('YYYY-MM-DD')
				params.startTime = `${today} ${this.wakeDownTime}:00`
				// if (this.type == 'today') {
				// 	params.startTime = `${today} ${this.wakeDownTime}:00`
				// } else {

				// }
				try {
					const res = await addSleepRecord(params)
					uni.hideLoading()
					if (res.code == 200) {
						uni.showToast({
							title: '操作成功'
						})
						setTimeout(() => {
							uni.$emit('refreshData')
							uni.navigateBack()
						}, 1500)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading()
				}
			},
			async update() {
				uni.showLoading({
					title: '加载中...'
				})
				let today = this.today.replaceAll('/', '-')
				let params = {
					userId: this.userId,
					bodyId: this.userInfo.id,
					id: this.recordId,
					endTime: '',
					startTime: ''
				}
                if (this.wakeDownTime == '00:00' &&this.wakeUpTime == '00:00') {
                    this.wakeUpTime = '23:59'
                }
				params.startTime = `${today} ${this.wakeDownTime}:00`
				params.endTime = `${today} ${this.wakeUpTime}:00`
				// if (this.type == 'today') {
				// } else {
				// 	let yesterday = dayjs(dayjs(today).subtract(1, 'day')).format('YYYY-MM-DD')
				// 	params.startTime = `${yesterday} ${this.wakeDownTime}:00`
				// }
				try {
					const res = await updateSleepRecord(params)
					uni.hideLoading()
					if (res.code == 200) {
						uni.showToast({
							title: '修改成功'
						})
						uni.$emit('refreshData')
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading()
				}
			},
			async del() {
				uni.showLoading({
					title: '加载中...'
				})
				let params = {
					id: this.recordId
				}
				try {
					const res = await delSleepRecord(params)
					uni.hideLoading()
					if (res.code == 200) {
						uni.showToast({
							title: '删除成功'
						})
						uni.$emit('refreshData')
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					}
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading()
				}
			},
			selectWakeUpTime() {
				this.showWakeUpTime = false
			},
			selectWakeDownTime() {
				this.showWakeDownTime = false
			}
		}
	}
</script>


<style lang="scss">
	page {
		min-height: 100%;
	}
</style>
<style lang="scss" scoped>
	.details {
		.update_time {
			width: 240rpx;
			height: 48rpx;
			margin: 48rpx auto 0;
			padding: 0 48rpx;
			line-height: 48rpx;
			color: #FFFFFF;
			font-size: 24rpx;
			background-color: #545DDE;
			border-radius: 24rpx;
		}

		.wakeUp,
		.wakeDown {
			width: 100%;
			margin-top: 96rpx;
			background: #FAFAFA;
			border-radius: 16rpx;
			padding: 0 48rpx;

			.days_tabs {
				display: flex;
				align-items: center;
				height: 80rpx;
				margin-bottom: 32rpx;

				.day {
					width: 100%;
					line-height: 76rpx;
					font-size: 24rpx;
					color: #666D7F;
					border-bottom: 2rpx solid #FFFFFF;
				}

				.current {
					border-bottom: 4rpx solid #545DDE;
				}
			}

			.u_t,
			.d_t {
				height: 118rpx;
				padding: 0 16rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 28rpx;
				color: #666666;

				.t-r {
					display: flex;
					flex-direction: column;
					align-items: center;
					color: #545DDE;

					.b-border {
						width: 98rpx;
						height: 2rpx;
						background-color: #545DDE;
						margin-top: 10rpx;
					}

					.time {
						font-weight: 500;
						font-size: 32rpx;
						font-family: PingFangSC-Medium, PingFang SC;
					}
				}
			}
		}

		.wakeUp {
			margin-top: 16rpx;
		}

		.large_button {
			position: fixed;
			bottom: 76rpx;
			left: 50%;
			transform: translateX(-50%);
		}
	}
</style>